package com.zyd.controller.log;

import com.zyd.constants.ErrorDef;
import com.zyd.context.HeaderContext;
import com.zyd.exception.BusinessException;
import com.zyd.io.page.PageBean;
import com.zyd.io.page.PageRequestBean;
import com.zyd.io.vo.res.ResBody;
import com.zyd.service.log.LogService;
import org.apache.poi.hssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;



@RestController
@RequestMapping("/log")
public class LogController {
    @Autowired
    private LogService service;

    @Autowired
    private ServletContext context;



    private final static Logger LOGGER = LoggerFactory.getLogger(LogController.class);


    @PostMapping(value = "/getLog", consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
    public ResBody getLog(@RequestBody PageRequestBean request) {
        try {
            ResBody resBody = new ResBody(ErrorDef.SUCCESS, "查询日志成功");
            PageBean<Map<String, Object>> ret = service.getLog(request);
            resBody.setData(ret);
            /**
             * 保存查询的条件 导出使用
             */
            context.setAttribute("logExcelParam"+ HeaderContext.get().get("userid"), request);
            return resBody;
        } catch (BusinessException e) {
            return new ResBody(e.getCode(), e.getMessage());
        } catch (Exception e) {
            LOGGER.error("", e);
            return new ResBody(ErrorDef.SYSTEM_ERROR, "查询日志失败");
        }
    }

    @GetMapping(value = "excelExport/{userid}")
    public void downloadAllClassmate(@PathVariable String userid, HttpServletResponse response) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("信息表");
        //记录操作日志
        service.addLog(userid,"导出日志信息");
        String fileName = "zyd_log" + ".xls";//设置要导出的文件的名字
        /**
         * 取出session中的条件
         */
        PageRequestBean logExcelParam = (PageRequestBean) context.getAttribute("logExcelParam"+userid);
        logExcelParam.put("pageSize",100000000);//设置最大
        logExcelParam.put("currentPage", 1);
        PageBean<Map<String, Object>> ret = service.getLog(logExcelParam);
        int rowNum = 1;
        String[] headers = {"用户名", "操作事项", "操作时间"};
        //headers表示excel表中第一行的表头
        HSSFRow row = sheet.createRow(0);
        //在excel表中添加表头
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
        //在表中存放查询到的数据放入对应的列
        for (Map<String, Object> entity : ret.getItems()) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue((String) entity.get("username"));
            row1.createCell(1).setCellValue((String) entity.get("operationalMatters"));
            row1.createCell(2).setCellValue((String) entity.get("operationTime"));
            rowNum++;
        }
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }

}